import os
import time
import win32com.client as win32
from win32com.client import constants
import pythoncom
from ..app.configs import AppConfig


def open_pptx(file: str, text: str) -> bool:
    print("正在搜索", text)
    software = AppConfig().pptx_default_software.lower()
    print(software)
    if software == "powerpoint":
        handler_app = win32.gencache.EnsureDispatch("PowerPoint.Application")
    elif software == "wps":
        handler_app = win32.gencache.EnsureDispatch("kwps.Application")
    else:
        raise ValueError(
            f"Not support this kind of software {software} to open doc(x) file"
        )
    # 设置Word应用可见
    handler_app.Visible = True

    if os.path.exists(file):
        presentation = handler_app.Presentations.Open(file)
    else:
        raise FileNotFoundError(file)
    print(type(handler_app.ActiveWindow))

    # powerpoint.Visible = True
    # 遍历幻灯片
    found = False
    for slide in presentation.Slides:
        # 获取幻灯片中的所有形状
        for shape in slide.Shapes:
            # 检查形状是否包含文本
            if hasattr(shape, "TextFrame") and shape.TextFrame.HasText:
                # 获取形状中的文本
                text_range = shape.TextFrame.TextRange
                if text_range is not None:
                    found_item = text_range.Find(text)
                    if found_item is not None:
                        # 跳转到已发现的文字
                        # try:
                        print(found_item)
                        # found_item.Select()
                        # except:
                        #     import traceback
                        #     traceback.print_exc()
                        print(f"在幻灯片 {slide.SlideIndex} 中找到了 {text}。")
                        presentation.Slides(slide.SlideIndex).Select()
                        found = True
                        break
    handler_app.Activate()
    return found
